import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router'
// 哈希路由及历史路由
import store from '../store/index.js'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/pages/login.vue'),
  },
  {
    path: '/pages',
    name: 'layout',
    component: () => import('../views/LayOut/LayOut.vue'),
    redirect: '/user',
    children: [
      {
        path: '/roses',
        name: 'roses',
        component: () => import('../views/pages/rolesList.vue'),
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('../views/pages/userList.vue'),
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
  /**
   * to 从哪儿来
   * from 到哪儿去
   * next() 只有执行 next(), 页面才会跳转
   */

  // 判断用户是否登录
  const userInfo = store.state.userInfo.userInfo
  if (!userInfo.username) {
    // 未登录，条转到 login
    if (to.path === '/login') {
      next()
      return
    }
    next('/login')
  } else {
    next()
  }
})

export default router
